const router = require('koa-router')();

const { createTask, getTaskById, getTasks, updateTask, deleteTask } = require('../controller/task');
const { SuccessResponse, ErrorResponse } = require('../model/Response');
const reminder = require('../lib/reminder');
const loginCheck = require('../middleware/loginCheck');
const taskRemind = require('../middleware/taskRemind');

router.prefix('/api/task');

router.use(loginCheck);

// create
router.post('/', async function (ctx, next) {
  const userId = ctx.session.userInfo.id;
  const {
    content,
    remindTime
  } = ctx.request.body;

  const res = await createTask(userId, content, remindTime);
  ctx.state.taskId = res.id;
  ctx.body = new SuccessResponse(res, '添加任务成功');
  await next();
}, taskRemind);

// list
router.get('/list', async function (ctx) {
  const userId = ctx.session.userInfo.id;
  const res = await getTasks(userId, ctx.query);
  ctx.body = new SuccessResponse(res);
});

// getById
router.get('/:id', async function (ctx) {
  const taskId = ctx.params.id;
  const res = await getTaskById(taskId);
  ctx.body = new SuccessResponse(res);
});

// update
router.put('/:id', async function (ctx, next) {
  const userId = ctx.session.userInfo.id;
  const taskId = ctx.params.id;
  const {
    content,
    isCompleted,
    remindTime
  } = ctx.request.body;

  const res = await updateTask(userId, taskId, content, isCompleted, remindTime);
  if (!res) {
    ctx.body = new ErrorResponse();
    return;
  }
  ctx.state.taskId = taskId;
  ctx.body = new SuccessResponse();
  await next();
}, taskRemind);

// delete
router.delete('/:id', async function (ctx, next) {
  const userId = ctx.session.userInfo.id;
  const taskId = ctx.params.id;

  const res = await deleteTask(userId, taskId);
  if (!res) {
    ctx.body = new ErrorResponse();
    return;
  }
  ctx.body = new SuccessResponse();
  ctx.state.taskId = taskId;
  await next();
}, async function (ctx) {
  return await reminder.removeTaskReminder(ctx.session.userInfo.id, ctx.state.taskId);
});


module.exports = router;
